package com.bcx.wind.workflow.imp.cmd.runtimecmd;

import com.bcx.wind.workflow.entity.WindTask;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;

import java.util.Map;

import static com.bcx.wind.workflow.message.ErrorCode.DATABASE_OPERATE_ERROR;
import static com.bcx.wind.workflow.message.ErrorCode.UPDATE_TASK_FAIL;

/**
 * 添加任务变量命令
 *
 * @author zhanglei
 */
public class AddTaskVariableCommand implements Command<Void> {

    /**
     * 任务变量
     */
    private Map<String,Object> variable;

    /**
     * 任务ID
     */
    private String  taskId;

    /**
     * 需要更新的任务
     */
    private WindTask task;

    public AddTaskVariableCommand(String taskId,Map<String,Object> variable){
        this.taskId = taskId;
        this.variable = variable;
    }

    @Override
    public Void executor(CommandContext context) {
        checkArgs(context);
        if(this.variable == null){
            return null;
        }
        this.task.variable().putAll(this.variable);
        //更新
        if(context.access().updateTaskInstance(this.task) != 1){
            WindError.error(DATABASE_OPERATE_ERROR,null);
        }
        return null;
    }


    private void checkArgs(CommandContext commandContext){
        if(taskId == null){
            WindError.error(UPDATE_TASK_FAIL,null,"taskId");
        }
        this.task = commandContext.access().getTaskInstanceById(taskId);
        if(this.task == null){
            WindError.error(UPDATE_TASK_FAIL,null,"windTask");
        }
    }

}
